import {iMicroApp, iMicroConfig, iMicroPageMeta, iMicroTabMeta} from "@peryl/micro-web";
import {MicroAppModule} from "./MicroAppModule";
import {globalComputed, reactive} from "@peryl/react-compose";
import {defer} from "@peryl/utils/defer";

export const microAppState = MicroAppModule.createRegistration((option) => {

  const state: iMicroApp['state'] = reactive({
    /*注册的子应用信息*/
    microConfigs: [] as iMicroConfig[],
    /*响应式可修改的标签信息数据*/
    tabs: [] as iMicroTabMeta[],
    /*当前激活的tab以及page*/
    current: globalComputed((): (null | { tab: iMicroTabMeta, page: iMicroPageMeta }) => {
      let activePage: iMicroPageMeta | undefined = undefined;
      let activeTab = state.tabs.find(tab => {
        activePage = tab.pages.find(i => i.show);
        return !!activePage;
      });
      return !!activePage && !!activeTab ? { tab: activeTab, page: activePage } : null;
    })
  });

  /**
   * 注册子应用
   * @author  韦胜健
   * @date    2024/1/31 14:17
   */
  option.registry = (...microConfigs: iMicroConfig[]) => {
    state.microConfigs.unshift(...microConfigs);
    /*注册子应用的时候，就立即初始化defer.loadMicroInfoMap以及defer.loadMicroReadyMap中对应的microConfig的dfd对象*/
    microConfigs.forEach(microConfig => {
      option.defer.loadMicroInfoMap[microConfig.id] = defer<any>();
      option.defer.loadMicroReadyMap[microConfig.id] = defer<any>();
    });
  };

  return state;
});
